package tree;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * ProjectName: MailSensor <br>
 *
 * @author sheng.dong <br>
 * @date 2018/8/29 17:04 <br>
 * Description: //TODO
 */
public class TreeCreator<T extends BaseTreeNode<T, ID>, ID> {

    public final List<T> nodes;

    public TreeCreator(List<T> nodes) {
        this.nodes = nodes;
    }

    public static void main(String[] args) {
        Node[] nodes = new Node[]{
                new Node(1, 0, "a"),
                new Node(2, 1, "b"),
                new Node(3, 1, "c"),
                new Node(4, 2, "d"),
                new Node(5, 0, "f"),
                new Node(6, 5, "g"),
                new Node(7, 0, "h"),
        };
        TreeCreator<Node, Integer> creator = new TreeCreator<>(Arrays.asList(nodes));
        Node root = creator.tree(new Node(0, null, "root"));
        List<Node> trees = creator.trees();



    }


    public boolean isRootNode(T node) {
        return Objects.equals(node.getPid(), node.rootPidValue());
    }

    public T parentNode(T node) {
        return nodes.stream().filter(t -> Objects.equals(node.getPid(), t.getId())).findAny().orElse(node);

    }

    public List<T> childrenNodes(T node) {
        return nodes.stream().filter(t -> Objects.equals(node.getId(), t.getPid()))
                .collect(Collectors.toList());
    }

    public T tree(T root) {
        List<T> childrenNodes = childrenNodes(root);
        if (childrenNodes != null && !childrenNodes.isEmpty()) {
            root.setSubNodes(childrenNodes);
            for (T node : childrenNodes) {
                tree(node);
            }
        }
        return root;
    }

    public List<T> trees() {
        List<T> trees = new ArrayList<>();
        nodes.forEach(pNode -> {
            if (isRootNode(pNode)) {
                trees.add(pNode);
            }
            pNode.setSubNodes(childrenNodes(pNode));
        });
        return trees;
    }


}
